package com.pearadmin.system.timedTask;

import com.alibaba.fastjson.JSON;
import com.pearadmin.system.service.ISysAxisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 定期删除redis数据库zset类型key键对应的过期value值
 */

@Slf4j
@Component //把此类托管给Spring
public class RedisPastKeyTask {

    @Resource
    private ISysAxisService sysAxisService;

    @Scheduled(cron = "0 0 0 1/1 * ?") // cron表达式，每天执行一次
    public void deleteRedisKey(){
        Jedis jedis=new Jedis();
        jedis.auth("root");

        //获取上个月的日期（上个月的今天）
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        Date date = cal.getTime();

        //日期转成JSON格式
        String dateTime=JSON.toJSONString(date);
//        System.out.println(dateTime);
//        System.out.println("-----------");
        //遍历redis中的zset键
        List<String> axisId=sysAxisService.selectAllAxisCount();
        for (String str : axisId) {
            jedis.zremrangeByScore(str,0,Double.parseDouble(dateTime));
        }
    }

}
